'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/dy_tv/kh/fillepisodeId 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			_id,
			album_id
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		//匹配seq
		function findObjectByName(arr, series) {
			var foundObject = arr.find((obj) => obj.seq === series);
			return foundObject;
		}


		//获取需要更新的分集数组
		let updataTVarrs = await vk.baseDao.select({
			dbName: "a_tv_series", // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: true, // 是否只返回rows数据，默认false
			pageIndex: 1, // 当前第几页
			pageSize: -1, // 每页条数
			whereJson: { // 条件
				tv_id: _id
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "series",
				type: "asc"
			}],
		});

		console.log("updataTVarrs====", updataTVarrs);
		//查询主剧
		let tv = await vk.baseDao.findByWhereJson({
			dbName: "dy_tv",
			whereJson: {
				album_id: album_id
			}
		});
		
		console.log("tv========",tv);

		if (tv == null) {
			res = {
				code: 1,
				msg: "短剧ID错误,仔细检查空格"
			}
			return res
		}

		console.log("tv._id===", tv._id);
		let dy_tv_id = tv._id

		console.log("dy_tv_id===", dy_tv_id);


		//从抖音拿到的数组
		let TVarrs = await vk.baseDao.select({
			dbName: "dy_tv_series", // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: true, // 是否只返回rows数据，默认false
			pageIndex: 1, // 当前第几页
			pageSize: -1, // 每页条数
			whereJson: { // 条件
				tv_id: dy_tv_id
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "seq",
				type: "asc"
			}],
		});
		console.log("TVarrs====", TVarrs);

		if (TVarrs) {
			//匹配修改episode_id
			let new_tv_data = updataTVarrs.map((item, index) => {
				let result = {};
				result = findObjectByName(TVarrs, item.series);
				console.log("result================104：" + result);
				if (result) {
					//匹配成功，进行替换
					console.log("result.episode_id" + result.episode_id);
					item.episode_id = result.episode_id;
				} else {
					console.log("================90" + result);
					console.log(`第${item.seq}集匹配失败`);
				}
				return item;
			});

			//匹配完之后触发批量函数更新分集
			if (new_tv_data) {
				for (var i = 0; i < new_tv_data.length; i++) {
					res.newInfo = await vk.baseDao.updateById({
						dbName: "a_tv_series",
						id: new_tv_data[i]._id,
						dataJson: {
							episode_id: new_tv_data[i].episode_id
						},
					});
				}
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}